package edu.gatech.ors.mrsim.core;

import java.util.ArrayList;

import org.apache.log4j.Logger;

import edu.gatech.ors.mrsim.io.conf.Configuration;
import edu.gatech.ors.mrsim.io.conf.PropertiesConfiguration;
import edu.gatech.ors.mrsim.io.logging.Logging;

public class Simulator {
	public static boolean TEST = true;
	public static boolean DEBUG = false;
	private static final Logger LOGGER = Logging.getInstance().getClassLogger(Simulator.class);
	private static Configuration config;
	private ArrayList<Simulation> simulations;
	private String[] commandLineIn;

	private static final String SIMULATIONS = "Simulations";

	public static void main(String[] args) {
		Simulator sim = new Simulator(args);
		sim.startSimulations();
	}

	private Simulator(String[] args) {
		commandLineIn = args;
		simulations = init(args);
	}

	public ArrayList<Simulation> init(String[] args) {
		if (TEST)
			config = PropertiesConfiguration.loadTest(true);
		else if (DEBUG)
			config = PropertiesConfiguration.loadDebug(true);
		else
			config = PropertiesConfiguration.loadCore(true);
		if (!config.containsKey(SIMULATIONS)) {
			config.setString(SIMULATIONS, "None");
			config.saveConfiguration();
		}
		LOGGER.debug("config loaded at " + config.getFile().getAbsolutePath());

		ArrayList<Simulation> newSimulations = new ArrayList<Simulation>();
		if (config.getStrings(SIMULATIONS).equals("None")) {
			LOGGER.error("Given config file empty or has no simulations, exiting program");
		} else {
			String[] names = config.getStrings(SIMULATIONS);
			for (String name : names) {
				Configuration simConfig = config;
				if (simConfig != null) {
					Simulation sim = new Simulation(name, simConfig);
					if (sim != null) {
						sim.loadValuesFromConfiguration();
						newSimulations.add(sim);
					}
				}
			}
			return newSimulations;
		}
		return null;
	}

	public void startSimulations() {
		if (simulations != null)
			for (Simulation sim : simulations)
				if (!sim.isStarted())
					sim.start();
	}
}
